<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/11
 * Time: 13:22
 */
namespace app\admin\controller;

use app\admin\model\Smspro as Smspros;
use app\common\Common;
use think\Request;

class Smspro extends Common
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $param   = $request->param();
        try {
            if(empty($param['name'])){
                $list = Smspros::all(null,'provider');
            }else{
                $list = Smspros::hasWhere('provider',['name'=>$param['name']])
                    ->with(['provider'])
                    ->select();
            }
            return json(['code'=>0,'msg'=>'','count'=>count($list),'data'=>$list]);
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        try {
            $data   = $request->param();
            $validate = validate('Smspro');
            if (!$validate->check($data)) {
                abort(409,$validate->getError());
            }else{
                $result = Smspros::create($data);
                return json($result);
            }
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        try {
            $data = Smspros::get($id);
            if ($data) {
                return json($data);
            } else {
                return abort(404, '配置不存在');
            }
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        try{
            $data   = $request->param();
            $result = Smspros::update($data, ['id' => $id]);
            return json($result);
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        try{
            $result = Smspros::destroy($id);
            return json($result);
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }
}